package com.dongnam.quanly.web.danhmuc.nganhang;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dongnam.quanly.common.controller.KhoHangController;
import com.dongnam.quanly.common.controller.NganHangController;
import com.dongnam.quanly.common.exceptions.DatabaseException;
import com.dongnam.quanly.common.model.KhoHang;
import com.dongnam.quanly.common.model.NganHang;
import com.dongnam.quanly.web.UserBean;
import com.dongnam.quanly.web.util.WebUtil;

@ManagedBean(name = "NganHangBean")
@SessionScoped
public class NganHangBean implements Serializable {

	private static final Logger logger = LoggerFactory.getLogger(NganHangBean.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@ManagedProperty(value = "#{UserBean}")
	private UserBean userBean;
	private NganHangModel nganHangModel;

	// for add KhoHang
	private NganHang nganHang;
	private boolean isEdit = false;
	// for download file
	private StreamedContent file;

	// for load danh sach phong ban
	private NganHangController nganHangController;
	private List<NganHang> listNganHang;

	// for edit phongBan
	private NganHang selectedNganHang;

	public NganHangBean() {
		super();
		nganHang = new NganHang();
		loadnganHang();
		// TODO Auto-generated constructor stub
	}

	public NganHangController getnganHangController() {

		if (nganHangController == null)
			nganHangController = new NganHangController();
		return nganHangController;
	}

	public void setnganHangController(NganHangController nganHangController) {
		this.nganHangController = nganHangController;
	}

	public void downloadFileCSV() {

		File excelfile = new File("NGAN_HANG.xls");
		List<NganHang> list = getnganHangController().findAll();
		int length = list.size();
		try {
			WritableWorkbook workbook = Workbook.createWorkbook(excelfile);
			WritableSheet sheet = workbook.createSheet("First Sheet", 0);

			// style for title
			WritableFont titlefont = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
			WritableCellFormat titleformat = new WritableCellFormat(titlefont);
			titleformat.setAlignment(Alignment.LEFT);
			titleformat.setWrap(false);

			// style for content
			WritableFont contentfont = new WritableFont(WritableFont.ARIAL, 13);
			WritableCellFormat contentformat = new WritableCellFormat(contentfont);
			contentformat.setAlignment(Alignment.LEFT);
			contentformat.setWrap(false);

			// thiet lap tieu de
			sheet.setColumnView(0, 30);
			sheet.setColumnView(1, 30);
			sheet.setColumnView(2, 30);
			sheet.setColumnView(3, 30);
			sheet.setColumnView(4, 30);
			sheet.setColumnView(5, 30);

			sheet.addCell(new Label(0, 0, "id", titleformat));
			sheet.addCell(new Label(1, 0, "Tên Viet Tat", titleformat));
			sheet.addCell(new Label(2, 0, "Ten Day du", titleformat));
			sheet.addCell(new Label(3, 0, "Ten tieng anh", titleformat));
			sheet.addCell(new Label(4, 0, "Dia chi", titleformat));
			sheet.addCell(new Label(5, 0, "Dien giai", titleformat));

			for (int i = 0; i < length; i++) {

				sheet.addCell(new Label(0, i + 1, String.valueOf(list.get(i).getNganHangID()), contentformat));

				sheet.addCell(new Label(1, i + 1, list.get(i).getTenVietTat(), contentformat));
				sheet.addCell(new Label(2, i + 1, list.get(i).getTenDayDu(), contentformat));
				sheet.addCell(new Label(3, i + 1, list.get(i).getTenTiengAnh(), contentformat));
				sheet.addCell(new Label(4, i + 1, list.get(i).getDiaChi(), contentformat));
				sheet.addCell(new Label(5, i + 1, list.get(i).getDienGiai(), contentformat));

			}

			workbook.write();
			workbook.close();

			file = new DefaultStreamedContent(new FileInputStream(excelfile), "application/csv", "NGAN_HANG.xls",
					"UTF-8");

		} catch (IOException | WriteException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	public void handleFileUpload(FileUploadEvent event) {
		logger.debug("process upload file ");
		Workbook w;
		boolean rollback = false;
		List<NganHang> list = new ArrayList<NganHang>();
		try {
			w = Workbook.getWorkbook(event.getFile().getInputstream());
			// Get the first sheet
			Sheet sheet = w.getSheet(0);
			// Loop over first 10 column and lines

			for (int row = 1; row < sheet.getRows(); row++) {

				logger.debug("row " + row);
				Cell cell_ma = sheet.getCell(0, row);
				Cell cell_tenvt = sheet.getCell(1, row);
				Cell cell_tendd = sheet.getCell(2, row);
				Cell cell_tenta = sheet.getCell(3, row);
				Cell cell_diachi = sheet.getCell(4, row);
				Cell cell_dienGiai = sheet.getCell(5, row);

				NganHang nh = new NganHang();
				nh.setNganHangID(String.valueOf(cell_ma.getContents()));

				nh.setTenVietTat(cell_tenvt.getContents());
				nh.setTenDayDu(cell_tendd.getContents());
				nh.setTenTiengAnh(cell_tenta.getContents());
				nh.setDiaChi(cell_diachi.getContents());
				nh.setDienGiai(cell_dienGiai.getContents());
				list.add(nh);
			}
		} catch (BiffException | IOException e) {
			e.printStackTrace();
			rollback = true;
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful : Database error : "
					+ e.getMessage(), "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}

		if (!rollback) {
			getnganHangController().batchSaveOrUpdate(list);
		}

		loadnganHang();
	}

	public void resetFormAdd() {
		nganHang = new NganHang();
	}

	public void notifyAdd() {
		isEdit = false;
		resetFormAdd();
	}

	public void notifyEdit(NganHang nganHang) {
		isEdit = true;
		this.selectedNganHang = nganHang;
		this.nganHang.fillnganHang(nganHang);
	}

	public void removeNganHang() {

		if (this.selectedNganHang != null) {
			getnganHangController().makeTransient(this.selectedNganHang);
			loadnganHang();
			listNganHang = getnganHangController().findAll();
		}

	}

	public void save() {

		RequestContext context = RequestContext.getCurrentInstance();
		try {
			if (isEdit) {
				logger.debug("Edit new NganHang");

				if (this.selectedNganHang != null) {

					getnganHangController().makeTransient(this.selectedNganHang);

					this.selectedNganHang.fillnganHang(this.nganHang);
					this.selectedNganHang.setUpdateBy(userBean.getUser().getUserId());

					getnganHangController().makePersistent(this.selectedNganHang);
					// change state of parent
					context.addCallbackParam("opSuccess", true);
				}

			} else {

				logger.debug("Add new NganHang :" + this.nganHang.getNganHangID());
				NganHang nganHang = new NganHang();
				nganHang.setCreateBy(userBean.getUser().getUserId());
				nganHang.setUpdateBy(userBean.getUser().getUserId());

				nganHang.fillnganHang(this.nganHang);

				getnganHangController().makePersistent(nganHang);
				listNganHang = getnganHangController().findAll();
				context.addCallbackParam("opSuccess", true);

			}
		} catch (DatabaseException e) {
			e.printStackTrace();
			logger.debug("Database error" + e.getMessage());
			context.addCallbackParam("opSuccess", false);

			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful : Database error : "
					+ e.getMessage(), "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}

		loadnganHang();

	}

	public void loadnganHang() {
		if (nganHangModel == null)
			nganHangModel = new NganHangModel();

		nganHangModel.init();
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public UserBean getUserBean() {
		return userBean;
	}

	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}

	public void reloadPage() {
		loadnganHang();
		WebUtil.redirect("/pages/danhmuc/nganHang.xhtml");
	}

	public NganHangModel getkhoHangModel() {
		return nganHangModel;
	}

	public void setnganHangModel(NganHangModel nganHangModel) {
		this.nganHangModel = nganHangModel;
	}

	public NganHang getnganHang() {
		return nganHang;
	}

	public void setnganHang(NganHang nganHang) {
		this.nganHang = nganHang;
	}

	public boolean isEdit() {
		return isEdit;
	}

	public void setEdit(boolean isEdit) {
		this.isEdit = isEdit;
	}

	public NganHangModel getNganHangModel() {
		return nganHangModel;
	}

	public void setNganHangModel(NganHangModel nganHangModel) {
		this.nganHangModel = nganHangModel;
	}

	public NganHang getNganHang() {
		return nganHang;
	}

	public void setNganHang(NganHang nganHang) {
		this.nganHang = nganHang;
	}

	public List<NganHang> getListNganHang() {
		if (listNganHang == null) {
			listNganHang = getnganHangController().findAll();
		}
		return listNganHang;
	}

	public void setListNganHang(List<NganHang> listNganHang) {
		this.listNganHang = listNganHang;
	}

	public NganHang getSelectedNganHang() {
		return selectedNganHang;
	}

	public void setSelectedNganHang(NganHang selectedNganHang) {
		this.selectedNganHang = selectedNganHang;
	}

}
